package freemind.controller;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import freemind.main.XMLElement;
import freemind.modes.browsemode.BrowseNodeModel;

public class Util {

	static ArrayList<NodeAdapterBase> criados,salvos;
	
	public static BufferedImage deixaTransparente(Image img,Color cor) throws InterruptedException{
		int w = img.getWidth(null);
		int h = img.getHeight(null);
		int r,g,b;
		
		int interval = 10;
		BufferedImage bufimg;
			
		bufimg = transformarBufferedImage(img,BufferedImage.TYPE_INT_ARGB);
		
		WritableRaster raster = bufimg.getRaster();
		int[] imageData = new int[4];
						
		for(int i=0;i<w;i++){
			for(int j=0;j<h;j++){
				
				raster.getPixel(i, j, imageData);
				r = imageData[0];
				g = imageData[1];
				b = imageData[2];
				
				if( ( r<= (cor.getRed()+interval) && ( r>=cor.getRed()-interval )) &&
					( g<= (cor.getGreen()+interval) && ( g>=cor.getGreen()-interval )) &&
					( b<= (cor.getBlue()+interval) && ( b>=cor.getBlue()-interval )) 
				   ){
					raster.setSample(i, j, 3, 0);
				}
				
				
			}
			
		}
		return bufimg;
		
	}	
	
	public static BufferedImage transformarBufferedImage(Image tmp,int type){
		
		BufferedImage retorno = new BufferedImage(tmp.getWidth(null),tmp.getHeight(null),type);
		Graphics2D g = retorno.createGraphics();
		
		g.drawImage(tmp,0,0,null);
		return retorno;
		
	}	
	
	public static String getToday(){
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
		return sdf.format(cal.getTime());
	}	
	

	public static ArrayList<NodeAdapterBase> getCriados(){
		return criados;
	}
	
	public static ArrayList<NodeAdapterBase> getSalvos(){
		return salvos;
	}
	
	public static void setCriadosESalvos(BrowseNodeModel node){
		
					
		if( node.isCreated() ){
			criados.add(node.getAdapter());			
			node.hasSaved();
		}
		else if( node.isChanged() ){			
			salvos.add(node.getAdapter());
			node.hasSaved();
		}

		
		for(int i=0;i<node.getChildCount();i++){
			BrowseNodeModel child = (BrowseNodeModel) node.getChildAtIgnoreFolded(i);			
			setCriadosESalvos(child);
		}		
		
		 
	}	

	public static void clear(){
		if( criados == null ){
			criados = new ArrayList<NodeAdapterBase>();
			salvos = new ArrayList<NodeAdapterBase>();
		}
	}
	
	
}
